package com.sky.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.common.utils.PageUtils;
import com.sky.common.utils.Query;

import com.sky.mall.product.dao.CategoryDao;
import com.sky.mall.product.entity.CategoryEntity;
import com.sky.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = getBaseMapper().selectList(null);
        List<CategoryEntity> categoryEntityTree = categoryEntities.stream()
                .filter((category) -> {
                    return category.getParentCid() == 0;
                })
                .map((category) -> {
                    category.setChildren(getChildren(category, categoryEntities));
                    return category;
                })
                .sorted((c1, c2) -> {
                    return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
                })
                .collect(Collectors.toList());
        return categoryEntityTree;
    }

    @Override
    public void removeByIds(List<Long> ids) {
        //逻辑删除-通过Entity设置逻辑删除字段实现
        getBaseMapper().deleteBatchIds(ids);
    }

    /**
     * 递归获取当前分类的子分类
     *
     * @param categoryEntity
     * @param categoryEntities
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream().
                filter((category) -> {
                    return category.getParentCid().equals(categoryEntity.getCatId());
                })
                .map((category) -> {
                    category.setChildren(getChildren(category, categoryEntities));
                    return category;
                })
                .sorted((c1, c2) -> {
                    return (c1.getSort() == null ? 0 : c1.getSort()) - (c2.getSort() == null ? 0 : c2.getSort());
                })
                .collect(Collectors.toList());
    }

}